<?php

require_once '../ctl/config.php';
set_time_limit(0);

function run() {
	require_once 'Zend/Http/Client.php';

	$pages = array();
	foreach (array('2009', '2010', '2011') as $year) {
		foreach (array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12') as $month) {
			$pages[] = "$year-$month-01";
		}
	}

	foreach ($pages as $p) {
		echo $p;
		$client = new Zend_Http_Client('http://kotomatrix.ru/topmonth/' . $p);
		$client->setConfig(array('timeout' => 30));
		$response = $client->request();
		$body = $response->getBody();
	
		//echo '<meta http-eqexuiv="Content-Type" content="text/html; charset=utf-8">';


		

		// $dom = new Zend_Dom_Query($body);
		// $containers = $dom->query('.article');

		// На котоматрикс нужные посты с <div style="margin: 5px;">
		preg_match_all('/<div style="margin: 5px;">\s+<br\/><img alt="([^"]+)" src="([^"]+)"/is', $body, $matches, PREG_SET_ORDER);
		//echo '<pre>';var_dump($matches);die();

		// На joyreactor все посты лежат внутри div class='article'
		foreach ($matches as $key => $match) {
			$info = array();
			
			$info['ext_id'] = $p . '-' . $key;
			$info['rating'] = 0;
			
			$tmp = mysql_query("select * from koto where ext_id = {$info['ext_id']}");
			$row = mysql_fetch_assoc($tmp);
			// Если пост уже существует - обновляем рейтинг и переходим к следующему
			if ($row) {
				continue;
			}

			// Заполняем остальные поля
			$info['image_url'] = $match[2];
			if (!$info['image_url']) {
				continue;
			}
			
			// Ссылку на сам пост
			$info['url'] = "http://kotomatrix.ru/topmonth/$p";
		
			// Название
			$info['title'] = iconv('WINDOWS-1251', 'UTF-8', $matches[1]);
			
			
			$date = date('Y-m-d H:i:s');
			$info['created'] = $date;
			$info['modified'] = $date;

			$query = '';
			foreach ($info as $k => $v) {
				$query .= "`$k` = '$v',";
			}
			$query = trim($query, ',');

			$query = "insert into koto set $query";
			echo $query . "\n";
		
			$result = mysql_query($query);
			if (!$result) {
				$e = mysql_error();
				echo $e . "\n";
				error_log($e);
			} 
		} // end foreach posts
	} // end foreach pages
} // end run function


function get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
	$innerHTML .= $child->ownerDocument->saveXML($child);
    }

    return $innerHTML;
} 

ob_start();
run();
$content = ob_get_contents();
$f = fopen('koto.log', 'a+');
fwrite($f, $content);
fclose($f);



